package lion.framework.core.web.views;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import lion.dev.io.MimeTypeUtil;
import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;
import lion.framework.core.web.anno.ViewType;

/**
 * 处理附件下载的视图类型
 *
 * 请求中需要传入
 * 
 * @param name
 *            文件名称
 * @param attach
 *            附件输入流
 *
 *            <pre>
 * time   2014 2014年2月26日 下午3:48:58
 * mail   hl_0074@sina.com
 *            </pre>
 *
 * @author lion
 */
@ViewType("attach")
public class AttachView implements IView {

	public static final String VIEW_TYPE = "attach";
	private String name;
	private static final int BUFFER_SIZE = 1024 * 500;// 500KB

	@Override
	public void render(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Object o = request.getAttribute("attach");

		if (o == null) { return; }
		if (!(o instanceof byte[] || o instanceof InputStream)) { return; }

		String fileName = (String) request.getAttribute("name");
		response.setContentType("application/octet-stream");
		if (StringUtils.isNotBlank(fileName)) {
			response.setContentType(MimeTypeUtil.getMimeType(fileName));
			Config config = ConfigManager.getConfig("framework");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, config.getString("framework.sysencoding", "UTF-8")));
		}

		if (o instanceof byte[]) {
			byte[] buf = (byte[]) o;
			response.setContentLength(buf.length);
			response.getOutputStream().write(buf);
		} else if (o instanceof InputStream) {
			InputStream is = (InputStream) o;
			response.setContentLength(is.available());
			OutputStream os = response.getOutputStream();
			response.setContentLength(is.available());
			try {
				int buffersize = is.available() > BUFFER_SIZE ? BUFFER_SIZE : is.available();
				byte[] buffer = new byte[buffersize];
				int len = -1;
				while ((len = is.read(buffer)) > -1) {
					os.write(buffer, 0, len);
				}
				os.flush();
			} finally {
				try {
					os.close();
					is.close();
				} catch (Exception e) {
				}
			}
		}
	}

	@Override
	public String getName() {

		return name;
	}

	@Override
	public String type() {

		return VIEW_TYPE;
	}

}
